import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../entity/CardEntity.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'AddCardPage.dart';
import 'EditCardPage.dart';
import '../../base/application.dart';
import '../../event/CardEvent.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_easyrefresh/material_footer.dart';

class CardListPage extends StatefulWidget {
  String type; //type =1  点击列表选择卡
  CardListPage({Key key, this.type}) : super(key: key);

  @override
  _CardListPageState createState() => _CardListPageState();
}

class _CardListPageState extends State<CardListPage>with WidgetsBindingObserver {
  double kMargin5 = ScreenUtil().setWidth(5);
  double kMargin20 = ScreenUtil().setWidth(20);

  List<CardEntity> articles = new List();
  int page = 1;
  String token = "";
 EasyRefreshController _controller = new EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });

    WidgetsBinding.instance.addObserver(this);
    APPLIC.eventBus.on<CardEvent>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        loadList();
      });
    });
  }

  loadList() async {
    FormData formData = new FormData.fromMap({
      "token": token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANKCARD_LIST, data: formData);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      articles.clear();
      // _easyRefreshKey.currentState.callRefreshFinish();
      _controller.finishRefresh();
      (userMap['data']['list'] as List).forEach((v) {
        articles.add(new CardEntity.fromJson(v));
      });
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观察者
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "银行卡",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        actions: <Widget>[
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              child: Text(
                '添加',
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                    color: Colors.black54),
              ),
              padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
            ),
            onTap: () {
              Navigator.of(context)
                  .push<String>(new MaterialPageRoute(builder: (context) {
                return new AddCardPage();
              })).then((value) {
                if (value != null) {
                  loadList();
                }
              });
            },
          )
        ],
      ),
      body: new Container(
        color: divideColor,
        child: new EasyRefresh(
           controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          child: ListView.separated(
              itemBuilder: _buildListItem,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 1,
                );
              },
              itemCount: articles.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          CardEntity model = articles[index];
          if (widget.type == '1') {
            // saveString(CARD_BANK, model.bank_name);
            // saveString(CARD_ID, model.id);
            // saveString(ACCOUNT, model.account);
            // Navigator.pop(context);
            Navigator.of(context).pop(model);
          } else {
            // var gasIds=model.gasid;
            Navigator.push(
                context,
                MaterialPageRoute(
                    //导航打开新视图
                    builder: (context) =>
                        EditCardPage(id: model.id) //打开第二个页面，并传值，传递值的名称是model
                    ));
          }
          // //处理点击事件
        },
        child: Container(
            color: Colors.white,
            margin: EdgeInsets.fromLTRB(
                kMargin5, ScreenUtil().setHeight(15), kMargin5, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  ),
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(l) ?? 0,
            ScreenUtil().setHeight(t) ?? 0,
            ScreenUtil().setWidth(r) ?? 0,
            ScreenUtil().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = new Image(
        image: AssetImage('images/icon_setup_bankcard.png'),
        width: ScreenUtil().setHeight(100),
        height: ScreenUtil().setHeight(100),
        fit: BoxFit.fill);
    return _pd(image, l: kMargin20, t: kMargin20, r: 5, b: kMargin20);
  }

  Widget _rightColumn(int index) {
    var name = Container(
        alignment: Alignment.bottomLeft,
        child: RichText(
            text: TextSpan(style: TextStyle(color: Colors.black), children: [
          TextSpan(
              text: articles[index].truename,
              style: TextStyle(fontSize: 14.0)),
          TextSpan(
              text: index == 0 ? '(默认)' : '',
              style: TextStyle(fontSize: 14.0, color: Colors.red)),
        ])));
    var bank = Container(
        alignment: Alignment.bottomLeft,
        child: RichText(
            text: TextSpan(style: TextStyle(color: Colors.grey), children: [
          TextSpan(
              text: articles[index].bank_name,
              style: TextStyle(fontSize: 14.0)),
          TextSpan(
              text: '(' + articles[index].account + ')',
              style: TextStyle(fontSize: 14.0)),
        ])));

    var right = Container(
      child: Column(
        children: <Widget>[name, bank],
      ),
    );
    return _pd(right, l: kMargin20, t: kMargin20, r: 5, b: 0);
  }
}
